"""
@ProjectName : StudentManagementSystem
@File        : DBUtil.py
@Author      : WorldWind(1772830365@qq.com)
@Address     : ChangSha - BoWeiFeng
@Date        : 2025/7/16 下午1:56
"""
import pymysql
from pymysql import cursors


# 操作数据库模块

class Database:
    def __init__(self):
        print(f'This is __init__ method. {self.get_class_name()} class startup')

    # 连接数据库
    @staticmethod
    def openDB(host, port, user, passwd, db):  # 主机,端口号,用户名,密码,数据库名
        dbObj = pymysql.connect(host=host, port=port, user=user, password=passwd, db=db, charset='utf8')
        cursor = dbObj.cursor(cursors.DictCursor)
        # print('执行')
        return dbObj, cursor

    @staticmethod
    def readAll(sql, cursor):
        cursor.execute(sql)
        record = cursor.fetchall()  # 获取查询结果
        return record

    @staticmethod
    def readOne(sql, cursor):
        cursor.execute(sql)
        record = cursor.fetchone()  # 获取查询结果 第一条
        return record

    @staticmethod
    def writeDB(sql, cursor):
        result = cursor.execute(sql)
        return result

    # 关闭数据库
    @staticmethod
    def closeDB(dbObj):
        dbObj.close()

    @classmethod
    def get_class_name(cls):
        return cls.__name__

    def __del__(self):
        print(f'This is __del__ method. The {self.get_class_name()} class has been recycled')


# d = Database()
# result = d.openDB('127.0.0.1',3306,'root','root','students')
# print(result)
if __name__ == '__main__':
    host = '127.0.0.1'
    port = 3306
    user = 'root'
    passwd = 'root'
    db = 'students'
    # 插入一条数据
    dbObj, cursor = Database.openDB(host, port, user, passwd, db)
    sql = (
        "INSERT INTO t_student(sno,name,age,phone,address,sex) VALUES ('s003','王五',15,'17753226638','China wuhan','男'),"
        "('s004','莉莉',16,'17753675523','China BeiJing','女')")
    Database.writeDB(sql, cursor)
    dbObj.commit()
